import common from '../vendor/common'
import '../scss/index.scss'
import util from './util'
import { 
  getIndexData,
  getIndexBannerList, 
  getIndexServerBtnList, 
  getIndexSysNotices, 
  getIndexRecommends, 
  getIndexHotBlocks, 
  getIndexBuildingRecommends, 
  getIndexIntroServer,
  getRegion,
  getLikeBuildings,
  postLookForHouse,
  postPeltHouse 
} from '../vendor/api' // 请求的接口数据
const Vue = common.Vue
const mui = common.mui
const Swiper = common.swiper
const Util = util(mui)
const axios = common.axios
const buildingList = common.buildingList
var VueBanner = null // 首页banner Vue对象
var VueBroadcast = null // 系统公告 Vue对象
var VueServerList = null // 服务按钮 Vue对象
var VueQualityList = null //精品推荐列表Vue对象
var VueHotBlock = null // 热门商圈Vue对象
var VueIntroBuilding = null // 推荐写字楼Vue对象
var VueintroServer = null // 推荐服务Vue对象
var VueareaList = null // 区域列表
var VueBuildingList = null // 猜你喜欢楼盘列表Vue对象
var swiperBanner = null // banner轮播对象
var swiperBroadcast = null // 系统公告轮播对象
var webview_building = null // 楼盘详情页webView
var webview_ServeDetail = null // 服务详情页面 预加载
const detailBanner = common.detailBanner
var titleNView = { //详情页原生导航配置
  backgroundColor: '#ffffff', //导航栏背景色
  titleText: '', //导航栏标题 Vuehouse.list.title
  titleColor: '#333333', //文字颜色
  type: 'transparent', // 默认样式样式
  autoBackButton: true, //自动绘制返回箭头
  splitLine: { //底部分割线
    color: '#efefef'
  }
}
try {
  mui.plusReady(function () {
    var selfWebView = plus.webview.currentWebview()
    // 预加载登录页
    mui.preload({
      url: 'login_new.html',
      id: 'login_new.html',
      styles:{
        popGesture: 'hide'
      }
    })
    // 预加载楼盘详情页
    mui.preload({
      url: 'building_detail.html',
      id: 'building_detail.html',
      styles:{
        popGesture: 'hide',
        "titleNView": titleNView
      }
    })
    // 预加载房源详情页
    // mui.preload({
    //   url: 'house_detail.html',
    //   id: 'house_detail.html',
    //   styles:{
    //     popGesture: 'hide',
    //     "titleNView": titleNView
    //   }
    // })
    var reCommedNView = { //详情页原生导航配置
      backgroundColor: '#ffffff', //导航栏背景色
      titleText: '', //导航栏标题
      titleColor: '#333333', //文字颜色
      type: 'default', // 默认样式样式
      autoBackButton: true, //自动绘制返回箭头
      splitLine: { //底部分割线
        color: '#efefef'
      }
    };
    webview_ServeDetail = mui.preload({
      url: 'serve_detail.html',
      id: 'serve_detail.html',
      styles: {
        "render": "always",
        "popGesture": "hide",
        "bounce": "vertical",
        "bounceBackground": "#efeff4",
        "titleNView": reCommedNView
      }
    })
    
    // 预加载精选楼盘列表
    mui.preload({
      url: 'reCommed.html',
      id: 'reCommed.html',
      styles:{
        popGesture: 'hide',
        "titleNView": reCommedNView
      }
    })
    // 下拉上拉插件初始化
    mui.init({
      swipeBack: false,
      pullRefresh: {
        container: '#pullrefresh',
        down: {
          style:'circle',
          callback: init_index
        },
        up: {
          height:150,//可选.默认50.触发上拉加载拖动距离
          auto:true,//可选,默认false.自动上拉加载一次
          contentrefresh : "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
          contentnomore:'没有更多数据了',//可选，请求完毕若没有更多数据时显示的提醒内容；
          callback: pullupRefresh
        }
      }
    });
    VueBanner = new Vue({ // 轮播图vue实例
      el: '#VueBanner',
      components: {
        detailBanner
      },
      data: {
        banner: []
      }
    })
    VueBroadcast =  new Vue({ // 系统公告vue实例
      el: '#VueBroadcast',
      data: {
        list: []
      }
    })
    VueServerList = new Vue({ // 服务列表vue实例
      el: '#VueServerList',
      data: {
        list: []
      },
      methods: {
        // 服务列表跳转方法
        skipServerList: function(data) {
          mui.fire(webview_ServeDetail, 'upData', data);
          //更改详情页原生导航条信息
          reCommedNView.titleText = data.name;
          webview_ServeDetail.setStyle({
            "titleNView": reCommedNView
          });
          setTimeout(function () {
            webview_ServeDetail.show('slide-in-right', 300);
          }, 150);
        },
        toServeList() {
          var indexWebView = plus.webview.currentWebview()
          mui.fire(indexWebView, 'changeTab', {tab: 3})
        }
      }
    })
    VueQualityList = new Vue({ // 精品推荐列表vue实例
      el: '#VueQualityList',
      data: {
        list: []
      },
      methods: {
        toBuidingList: function(item) {
          var buildingListWebView = plus.webview.getWebviewById('reCommed.html')
          mui.fire(buildingListWebView, 'pushData', { data: item })
          setTimeout(function () {
            buildingListWebView.show("slide-in-right", 300)
          }, 150)
        }
      }
    })
    VueHotBlock = new Vue({ // 热门商圈vue实例
      el: '#VueHotBlock',
      data: {
        list: []
      },
      methods: {
        // 跳转楼盘列表并相关id区域
        skipBuildingList: function(area_guid, block_guid) {
          var buildingListWebView = plus.webview.getWebviewById('/home/build_index.html')
          mui.fire(buildingListWebView, 'searchArea', { area_guid: area_guid, block_guid: block_guid })
          var indexPage = plus.webview.getLaunchWebview()
          mui.fire(indexPage, 'changeTab', {tab: 2});
        }
      }
    })
    VueIntroBuilding = new Vue({ //  推荐写字楼vue实例
      el: '#VueIntroBuilding',
      data: {
        list: [],
        permitClick: true
      },
      methods: {
        tobuildingDetail: function(item) {
          if (!this.permitClick) {
            return false
          }
          this.permitClick = false
          var webview_building = plus.webview.getWebviewById('building_detail.html')
          mui.fire(webview_building, 'createdData',{
            item:item
          })
          var self = this
          setTimeout(function () {
            webview_building.show("slide-in-right", 300)
            setTimeout(function() {
              self.permitClick = true
            }, 300)
          }, 150)
        }
      }
    })
    VueintroServer = new Vue({ // 推荐服务
      el: '#VueintroServer',
      data: {
        first: {},
        list: []
      },
      methods: {
        // 服务列表跳转方法
        skipServerList: function(name, id, detail_url) {
          mui.fire(webview_ServeDetail, 'upData', { name: name, id: id, detail_url: detail_url});
          //更改详情页原生导航条信息
          reCommedNView.titleText = name;
          webview_ServeDetail.setStyle({
            "titleNView": reCommedNView
          });
          setTimeout(function () {
            webview_ServeDetail.show('slide-in-right', 300);
          }, 150);
        }
      }
    })
    VueareaList = new Vue({ // 区域列表
      el: '#areaList',
      data: {
        list: []
      },
      methods: {
        // 跳转楼盘列表并相关id区域
        skipBuildingList: function(id) {
          var buildingListWebView = plus.webview.getWebviewById('/home/build_index.html')
          mui.fire(buildingListWebView, 'searchArea', { area_guid: id, block_guid: 'all', })
          var indexPage = plus.webview.getLaunchWebview()
          mui.fire(indexPage, 'changeTab', {tab: 2});
        }
      }
    })
    VueBuildingList = new Vue({ // 猜你喜欢vue实例
      el: '#listApp',
      data: {
        list: [], // 列表数据
        page: 1 // 当前页数
      },
      components: { buildingList }
    })
    // 初始化页面
    Util.initIndex();
    init_index(true); // 初始化首页数据
    // 立即预约点击事件
    mui('body').on('tap', 'button#addBook', function(){
      // 拿到手机号
      var tel = document.getElementById('telInput').value
      if (tel === '') {
        mui.toast('请输入手机号')
        return
      }
      var telRpx = /^\+?[1-9][0-9]*$/
      if (!telRpx.test(tel) || tel.length !== 11) {
        mui.toast('请输入正确的11位手机号')
        return
      }
      document.getElementById('telInput').blur()
        mui('#popover').popover('show')
    })
    // 委托找房
    mui('body').on('tap', '#lookForHouse', function() {
      var tel = document.getElementById('telInput').value
      postLookForHouse({ tel: tel, page_source: '首页-委托找房', source: 5, demand: 2 }).then(res => {
        mui('#popover').popover('hide')
        document.getElementById('telInput').value = ''
        plus.nativeUI.toast('信息提交成功，楚楼网30分钟内联系您',{ duration:'long', type:'div' })
      })
      
    })
    // 投放房源
    mui('body').on('tap', '#pletHouse', function() {
      var tel = document.getElementById('telInput').value
      postPeltHouse({ tel: tel, page_source: '首页-投放房源', source: 5, demand: 1 }).then(res => {
        mui('#popover').popover('hide')
        document.getElementById('telInput').value = ''
        plus.nativeUI.toast('信息提交成功，楚楼网30分钟内联系您',{ duration:'long', type:'div' })
      })
    })
  })
}catch(e) {
  console.log('首页出错啦')
}
var mask = mui.createMask();
/**
 * 首页初始化方法
 */
var waitUI = null
function init_index(launchStatus = false) {
  plus.nativeUI.closeWaiting()
  if (swiperBroadcast !== null) {
    swiperBroadcast.destroy(true, true) // 销毁系统公告轮播对象
  }
  if (launchStatus) {
    waitUI = plus.nativeUI.showWaiting("加载中")
    mask.show()
  }
  if (window.plus && plus.networkinfo.getCurrentType() === plus.networkinfo.CONNECTION_NONE){
    plus.nativeUI.toast('未检测到网络连接，请打开wifi或手机移动网络',{ duration:'long', type:'div' })
    return false
  }
  getIndexData().then(res => {
    VueBanner.banner = [
      {
        url: '../images/temp_index_1.png',
        type: 'H5'
      },
      // {
      //   banner: '../images/temp_index_1.png',
      //   type: 'house_detail',
      //   url: '15'
      // }
    ]
     // 实例化banner轮播
     VueBroadcast.list = res.data.systemNotices// 系统公告赋值
     // 实例化系统公告轮播
    VueBroadcast.$nextTick(function() {
      swiperBroadcast = new Swiper('#swiperBroadcast', { // 实例化系统公告轮播
        loop:true,
        autoplay: 3000,
        effect : 'slide',
        direction : 'vertical',
        autoplayDisableOnInteraction:false,
        paginationClickable:true
      })
    })
     // 服务列表赋值
     VueServerList.list = res.data.services
     // 精品推荐列表赋值
     VueQualityList.list = res.data.recommends
     // 热门商圈赋值
     VueHotBlock.list = res.data.hotBlocks
     // 写字楼推荐赋值
     VueIntroBuilding.list = res.data.buildingRecommends
     // 推荐服务赋值
     VueintroServer.first = res.data.serviceRecommends.first
     VueintroServer.list = res.data.serviceRecommends.second
     VueareaList.list = res.data.areas
     mui('#pullrefresh').pullRefresh().endPulldownToRefresh()
     mui('#pullrefresh').pullRefresh().refresh(true)
     if (waitUI !== null) {
       setTimeout(function() {
         waitUI.close()
         mask.close()
       }, 1000)
     }
  })
  // 楼盘数据
  getLikeBuildings().then(res => {
      VueBuildingList.list = res.data.data
     VueBuildingList.page = parseInt(res.data.current_page) + 1
  })
}
// 下拉刷新
function pullupRefresh() {
  if (VueBuildingList.page === 1) {
    mui('#pullrefresh').pullRefresh().endPullupToRefresh(false)
    return false
  }
  getLikeBuildings({page: VueBuildingList.page}).then(res => {
    mui('#pullrefresh').pullRefresh().endPullupToRefresh(false)
    if (res.data.data.length === 0) {
      mui('#pullrefresh').pullRefresh().endPullupToRefresh(true)
      return
    }
    for(var i in res.data.data){
      VueBuildingList.list.push(res.data.data[i])
    }
    VueBuildingList.page = parseInt(res.data.current_page) + 1
  })
}
function onNetChange() {
  if (window.plus && plus.networkinfo.getCurrentType() === plus.networkinfo.CONNECTION_NONE){
    plus.nativeUI.toast('检测到您关闭了网络连接，请打开wifi或手机移动网络')
    return false
  }
  plus.nativeUI.closeWaiting();
  plus.nativeUI.closeToast();
  plus.runtime.restart();
}
document.addEventListener("netchange", onNetChange, true)